#include "mainlayoutview.h"
#include "ui_mainlayoutview.h"
#include <QDebug>
#include <QString>
#include <QCryptographicHash>
#include <QSqlQuery>

const QString BEFORE_CODE = "WHHCFcom";
const QString AFTER_CODE = "cn_whccf";

MainLayoutView::MainLayoutView(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainLayoutView)
{
    ui->setupUi(this);
}

MainLayoutView::~MainLayoutView()
{
    delete ui;

}


void MainLayoutView::on_btn_login_clicked()
{
    QString strUsername = ui->editusername->text();
    QString strPassword = ui->editpassword->text();

    strPassword = strToMd5(strPassword);
    qDebug() << "final password =>" << strPassword;

    // 登录
    QString resStr = QString("SELECT name, password FROM user WHERE name='%1' AND password='%2'").arg(strUsername).arg(strPassword);
    qDebug() << "resStr" << resStr;
    QSqlQuery resQuery;
    if(resQuery.exec(resStr))
    {
        qDebug() << "登录成功";
    }
    else
    {
        qDebug() << "登录失败";
    }

}


void MainLayoutView::on_btn_quit_clicked()
{
    this->parentWidget()->show();
    this->hide();
}


void MainLayoutView::on_btn_register_clicked()
{
    QString strUsername = ui->editusername->text();
    QString strPassword = ui->editpassword->text();

    strPassword = strToMd5(strPassword);
    qDebug() << "final password =>" << strPassword;

    // 注册
    QString resStr = QString("INSERT INTO user(name, password) VALUES('%1', '%2')").arg(strUsername).arg(strPassword);
    qDebug() << "resStr" << resStr;
    QSqlQuery regQuery;
    if(regQuery.exec(resStr))
    {
        qDebug() << "注册成功";
    }
    else
    {
        qDebug() << "注册失败";
    }

}

QString MainLayoutView::strToMd5(QString str)
{
    QString strMd5;
    QByteArray qba;
    QString befStr = BEFORE_CODE + str + AFTER_CODE;
    qDebug() << "befStr" << befStr;
    qba = QCryptographicHash::hash(befStr.toLatin1(), QCryptographicHash::Md5);
    qba = QCryptographicHash::hash(qba, QCryptographicHash::Md5);
    strMd5.append(qba.toHex());
    return strMd5;

}

